package swing.chapter03;

import swing.util.SwingConsle;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 弹出式菜单
 */
public class Popup extends JFrame {
    private JPopupMenu popup = new JPopupMenu();
    private JTextField t = new JTextField(10);

    public Popup(){
        setLayout(new FlowLayout());
        add(t);

        ActionListener al = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = ((JMenuItem) e.getSource()).getText();
                t.setText(text);
            }
        };

        JMenuItem m = new JMenuItem("Hither");
        m.addActionListener(al);
        popup.add(m);

        m = new JMenuItem("Yon");
        m.addActionListener(al);
        popup.add(m);

        m = new JMenuItem("After");
        m.addActionListener(al);
        popup.add(m);

        popup.addSeparator();

        m = new JMenuItem("Stay Here");
        m.addActionListener(al);
        popup.add(m);

        PopupListener pl = new PopupListener();
        // 当前 JFream 中添加鼠标弹出菜单监听
        addMouseListener(pl);
        t.addMouseListener(pl);
    }

    class PopupListener extends MouseAdapter{
        @Override
        public void mouseReleased(MouseEvent e) {
            if(e.isPopupTrigger()){
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    public static void main(String[] args) {
        SwingConsle.run(new Popup(), 300, 200);
    }
}


